#!/usr/bin/python

'''
viewmyportfolio version 0.2

Release Date: 11 Aug 2010
Author: Minn Myat Soe [mmyatsoe@gmail.com]
--------------------------------------------------------------------------------
USAGE:

To use default portfolio file 'portfolio.dat' in current directory
~$ ./viewmyportfolio.py

To use different data file 'mynewfile.dat'
~$ ./viewmyportfolio.py -f mynewfile.dat

To display help and basic usage:
~$ ./viewmyportfolio.py -h

To enable debug mode:
~$ ./viewmyportfolio.py -d 

To view portfolio performance:
~$ ./viewmyportfolio.py -p

To view intra-day data (future implementation):
~$ ./viewmyportfolio.py -i

--------------------------------------------------------------------------------
SOFTWARE LICENSE

Copyright (c) 2010 Minn Myat Soe

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import pyql
import optparse
import logging
import urllib2
import json
from sys import argv, exit
from string import split, strip

TRUE = 1
FALSE = 0
logger = logging.getLogger( 'viewmyportfolio' )

def readData( infile, delim ):

   logger.debug( 'Opening data file \'' + infile + '\'' )
   try:
      input = open( infile, 'r' )
   except:
      logger.exception( 'Error opening file \'' + infile + '\'.' )
      exit( 1 )

   logger.debug( 'Done' )
   logger.debug( 'Reading stock quotes from \'' + infile + '\'.' )

   portfolio      = []
   sharesOwned    = []
   pricePaid      = []

   for line in input.readlines():
      x = split( line, delim )
      if len( x ) < 3:
         logger.error( infile + ', line ' + line + 'Bad format\n' )
         exit( 1 )

      ticker = strip( x[0] )
      owned  = strip( x[1] )
      paid   = strip( x[2] )
      # portfolio.append( "'" + ticker + "'" )
      portfolio.append( ticker )
      sharesOwned.append( owned )
      pricePaid.append( paid )

      logger.debug( "Read: ticker->" + ticker + ", owned->" + owned + ", paid->" + paid )
   input.close()

   logger.debug( "Done. All tickers have been loaded" )

   try:
       info = pyql.lookup( portfolio )
   except urllib2.HTTPError, e:
       logger.exception("HTTP Error: ", e.code)
   except urllib2.URLError, e:
       logger.exception("URL Error: ", e.reason)
               
   index = 0
   for result in info:
      result['SharesOwned'] = sharesOwned[index]
      result['PricePaid'] = pricePaid[index]
      index += 1

   return info

def printPerformance( p ):
   logger.debug( 'Printing Portfolio Performance...' )
   totalValue = 0
   totalGain = 0
   totalBought = 0
   print
   print "%-17s %12s %8s %12s %12s %12s" % ( 'Stock', 'Ticker', 'Price', 'Bought', 'Market', 'Gain/Loss' )
   print '-------------------------------------------------------------------------------'

   for stock in p:
      price = float( stock['LastTradePriceOnly'] )
      shares = int( stock['SharesOwned'] )
      value = price * shares
      bought = float( stock['PricePaid'] ) * shares
      totalBought += bought
      gain = value - bought
      gainInPercent = ( gain / bought ) * 100
      totalValue += value
      totalGain += gain
      totalGainPercent = ( totalGain / totalBought ) * 100

      print "%-17s %12s %8.2f %12.2f %12.2f %12.2f (%3.2f%%)" % ( strip( stock['Name'] ), stock['Symbol'], price, bought, value, gain, gainInPercent )

   print "\nTotal portfolio value : %10.2f" % totalValue
   print   "Net Gain/Loss         : %10.2f (%.2f%%)" % ( totalGain, totalGainPercent )

def printSummary( p ):
   logger.debug( 'Printing Portfolio Summary' )
   totalValue = 0
   print
   print "%-17s %12s %8s %12s" % ( 'Stock', 'Ticker', 'Price', 'Market' )
   print '------------------------------------------------'

   for stock in p:
      price = float( stock['LastTradePriceOnly'] )
      shares = int( stock['SharesOwned'] )
      value = price * shares
      bought = float( stock['PricePaid'] ) * shares
      gain = value - bought
      totalValue = totalValue + value

      print "%-17s %12s %8.2f %12.2f" % ( strip( stock['Name'] ), stock['Symbol'], price, value )

   print "\nTotal portfolio value : %10.2f" % totalValue

def initDebug( logLevel ):
   logging.basicConfig( level = logLevel,
                       format = '%(asctime)s %(levelname)s %(name)s - %(message)s' )

def main():
   # TODO: To convert to argsparser since OptParser is deprecated since 2.7
   usage = 'Usage: %prog [options]'
   version = "%prog 0.1"
   parser = optparse.OptionParser( usage = usage, version = version )

   parser.add_option( '-d', '--debug', help = 'enable debug mode',
                                        action = 'store_const',
                                        const = logging.DEBUG,
                                        dest = "debug",
                                        default = logging.ERROR )

   parser.add_option( '-f', '--file', help = 'use different data file',
                                        dest = 'dataFile',
                                        type = 'string',
                                        metavar = 'FILE',
                                        default = 'portfolio.dat' )

   parser.add_option( '-s', '--separator', help = 'set new data separator',
                                            dest = 'delimiter',
                                            type = 'string',
                                            metavar = 'SEPARATOR',
                                            default = '|' )

   parser.add_option( '-p', '--performance', help = 'view portfolio performance',
                                                action = 'store_const',
                                                const = 1,
                                                dest = "displayAction",
                                                default = 0 )

   parser.add_option( '-i', '--intraday', help = 'view intra-day statistics',
                                            action = 'store_const',
                                            const = 2,
                                            dest = "displayAction" )

   ( options, args ) = parser.parse_args()

   initDebug( options.debug )

   stockInfo = readData( options.dataFile, options.delimiter )


   if options.displayAction == 0:
      printSummary( stockInfo )
   elif options.displayAction == 1:
      printPerformance( stockInfo )
   elif options.displayAction == 2:
      printPerformance( stockInfo )

   logger.debug( 'Exiting main()' )

if __name__ == '__main__':
   main()

